package com.yuyou.hxyy.service.api.service.impl;

import com.yuyou.hxyy.service.api.entity.WordUrl;
import com.yuyou.hxyy.service.api.mapper.WordUrlMapper;
import com.yuyou.hxyy.service.api.service.IQiniuService;
import com.yuyou.hxyy.service.api.service.IWordUrlService;
import com.yuyou.hxyy.service.api.util.Sequence;
import com.yuyou.hxyy.service.api.voice.YoudaoApiUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.ByteArrayInputStream;
import java.util.Date;

@Service
public class WordUrlServiceImpl implements IWordUrlService {

    @Autowired
    private WordUrlMapper mapper;

    @Autowired
    private IQiniuService qiniuService;

    @Override
    public int deleteByPrimaryKey(Long wordUrlId) {
        return mapper.deleteByPrimaryKey(wordUrlId);
    }

    @Override
    public int insert(WordUrl record) {
        return mapper.insert(record);
    }

    @Override
    public WordUrl selectByPrimaryKey(Long wordUrlId) {
        return mapper.selectByPrimaryKey(wordUrlId);
    }

    @Override
    public int updateByPrimaryKeySelective(WordUrl record) {
        return mapper.updateByPrimaryKeySelective(record);
    }

    @Override
    public WordUrl findByKey(String key) {
        return mapper.findByKey(key);
    }

    @Override
    public boolean addUrl(String key) {
        WordUrl wordUrl = new WordUrl();
        wordUrl.setCreateTime(new Date());
        wordUrl.setWordUrlId(Sequence.getSequence().nextId());
        wordUrl.setKey(key);

        try {
            byte[] b = YoudaoApiUtils.getVoice(key , 5);
            String url = qiniuService.upload(new ByteArrayInputStream(b) , "voice");
            wordUrl.setValue(url);
            mapper.insert(wordUrl);
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


}